package com.khotyn.heresy.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.khotyn.heresy.bean.PictureBrief;
import com.khotyn.heresy.bean.PictureDetail;
import com.khotyn.heresy.bean.UserBrief;
import com.khotyn.heresy.dao.PictureDAO;
import com.khotyn.heresy.dao.UserDAO;
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedOutput;

/**
 * 生成rss订阅xml文件的控制器 目前仅支持订阅单个用户，请求订阅的url中需要提供订阅用户id 请求的uri为:/feed.html
 * 目前设置默认的rss版本为rss2.0
 * 
 * @author jinlingjie
 * 
 */
@Controller
@RequestMapping("/feed.html")
public class RSSController {
	private static final String feedType = "rss_2.0"; // 默认设置rss版本为rss 2.0
	private static final String MIME_TYPE = "application/xml; charset=UTF-8";
	private static final int MAX_PICTURE_NUM = 10; // 默认最近图片数量30

	private String url; // 网站url

	@Autowired
	private UserDAO userDAO;

	@Autowired
	private PictureDAO pictureDao;

	/**
	 * 获取rss种子 从数据库中通过用户id获取rss信息，并返回整合后的种子
	 * 
	 * @param uid 用户id，用于查询特定用户的图片
	 * @return 种子对象，完整rss内容的封装
	 */
	private SyndFeed getFeed(int uid) {
		UserBrief userBrief = userDAO.selectUserBriefInfoByUserId(uid);

		SyndFeed feed = new SyndFeedImpl(); // 声明种子对象

		// 初始化种子
		feed.setTitle("shutter网络相册——" + userBrief.getUserName());
		feed.setDescription(userBrief.getUserName() + "最近上传的图片");
		feed.setEncoding("utf-8");

		List<SyndEntry> entries = new ArrayList<SyndEntry>();
		SyndContent description;
		SyndEntry entry;
		List<PictureBrief> picList = pictureDao.selectRecentUploadPicture(uid, MAX_PICTURE_NUM); // 获得该用户最近上传的图片

		// 循环获取上传图片中的信息，构造rss项
		for (PictureBrief pictureBrief : picList) {
			try {
				PictureDetail pictureDetail = pictureDao.selectPicByPicID(pictureBrief.getPictureID());

				if (!pictureDetail.getFlagLimit().equalsIgnoreCase("public")) {
					continue;
				}

				entry = new SyndEntryImpl();
				entry.setTitle(pictureBrief.getName());
				entry.setAuthor(userBrief.getUserName());
				entry.setLink(url + "/picture.html?pictureID" + pictureBrief.getPictureID());
				entry.setPublishedDate(pictureDetail.getUploadTime());

				description = new SyndContentImpl();
				description.setType("text/html");
				String value = "<link href='./css/PhotoCenter.css' rel='stylesheet' type='text/css'/><img src='./pic/"
						+ pictureBrief.getThumbLocation() + "'  class='thumbImage'/>";
				description.setValue(value);

				entry.setDescription(description);
				entries.add(entry);
			} catch (Exception e) {
			}
		}

		feed.setEntries(entries);

		return feed;
	}

	/**
	 * @param userDAO the userDAO to set
	 */
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	/**
	 * @param pictureDao the pictureDao to set
	 */
	public void setPictureDao(PictureDAO pictureDao) {
		this.pictureDao = pictureDao;
	}

	/**
	 * 接受rss请求，并从response中输出rss的xml文件
	 * 
	 * @param uid
	 * @param response
	 * @param request
	 */
	@RequestMapping
	public void createRssXML(@RequestParam(value = "uid", required = false) String uid, HttpServletResponse response, HttpServletRequest request) {
		if (uid == null)
			return;

		url = request.getRemoteAddr() + ":" + request.getLocalPort() + request.getContextPath();

		int UID = 0;
		try {
			UID = Integer.parseInt(uid);
		} catch (NumberFormatException e) {
			e.printStackTrace();
			return;
		}

		SyndFeed feed = getFeed(UID);
		feed.setFeedType(feedType);
		feed.setLink(url + "/");

		SyndFeedOutput output = new SyndFeedOutput();

		response.setContentType(MIME_TYPE);

		try {
			output.output(feed, response.getWriter());
		} catch (IOException e) {
			e.printStackTrace();
		} catch (FeedException e) {
			e.printStackTrace();
		}

	}
}
